
$(function() {
	var roleId = $("#id").val();
	/**
	 * zTree设置
	 */
	var setting = {
		check : {
			enable : true,
			chkboxType : {
				"Y" : "ps",
				"N" : "ps"
			}
		},
		data : {
			key : {
				name : "resourceName"
			},
			simpleData : {
				enable : true,
				idKey : 'id',
				pIdKey : 'parentId',
				rootPId : "-1"
			}
		}
	};
	$.ajax({
		url : rootPath + "/resource/getRoleResourceList",
		async : false,
		dataType : 'json',
		data : {
			roleId : roleId
		},
		type : 'post',
		success : function(nodes) {
			var treeObj = $.fn.zTree.init($("#zTree"), setting, nodes);
			treeObj.expandAll(true);
		}
		
	});

	
	$("#btn_save").click(function(){
		$("#roleEdit").submit();
		return false;
	});
 
	
	//新增表单校验
 	$("#roleEdit").validate({
 		rules: {
 			roleName:{
 				required:true,
        		minlength:3,
        		maxlength:20
        	}
 		},
 		messages: {
        	roleName:{
        		required: '请填写角色名称',
        		minlength: '角色名称至少6位',
        		maxlength: '角色名称至多20位'
        	}
 		},
 		errorPlacement: function(error, element) { //错误信息位置设置方法
 			error.insertAfter(element);
		},
 		submitHandler: function(form){
 			if (!$(form).valid()) {
				return false;
			}
 			var treeObj = $.fn.zTree.getZTreeObj("zTree");
 			var nodes = treeObj.getCheckedNodes(true);
 			var resourceIds = [];
 			for (var i = 0; i < nodes.length; i++) {
 				resourceIds.push(nodes[i].id);
 			}
 			var reStr = JSON.stringify(resourceIds);
 			$.ajax({
				dataType: "json",
				url:rootPath+"/resource/updateRoleResource",
				type:"POST",
				data : {roleId : $("#id").val(),
					roleName:$("#roleName").val(),
					roleIntro:$("#roleIntro").val(),
					resourceIds : reStr
					},
				success : function(data) {
					if(data.code=='1'){
						showSuccess("编辑成功！",function(){
							window.location.href=rootPath+"/role/listRolePage";
						});
	 					}else{
	 						showErr("编辑失败！");
	 					}
				}
				
			});
         }
 	});
	

	$("#btn_back").click(function() {
		location.href = rootPath + "/role/listRolePage";
	});
});
